package com.xhwl.centiotdata.handler.org.impl;

import com.xhwl.centiotdata.handler.org.OrgFactory;
import com.xhwl.centiotdata.handler.org.OrgHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.suppliersystem.itc.UserItcHandler;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * ITC组织同步
 *
 * @author wangyiling
 * @description
 * @date 2022/9/16
 */
@Service
@Slf4j
public class OrgItcHandler extends OrgHandler {
    @Autowired
    private UserItcHandler userItcHandler;
    @Resource
    private IOrgInfoService iOrgInfoService;

    @Autowired
    IProjectCentService iProjectCentService;

    @Override
    public void createOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        log.error("同步新增空间路址-----config===" + config + "----organizations===" + organizations);
        config.setProjectId(organizations.get(0).getProjectId());
        if (config.getProjectId() != null && config.getProjectId() > 0) {//组织topic消息 无projectid ;空间路址才有projectID
            initLocation(config);
        }
        initOrganization(config, organizations.get(0).getEnterpriseId());
//        organizations.forEach(org -> {
//            // 如果创建的组织是ORG才能同步到海康
//            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue() ||org.getType() == OrganizationTypeEnum.UNIT.getId().intValue() || org.getType() == OrganizationTypeEnum.FLOOR.getId().intValue()|| org.getType() == OrganizationTypeEnum.AREA.getId().intValue()|| org.getType() == OrganizationTypeEnum.BUILDING.getId().intValue()) {
//                HashMap<Integer, String> parent = new HashMap<>();
//                OrgInfo result = iOrgInfoService.getOrgInfo(org.getParentId(), config.getProductId());
//                if(null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
//                    parent.put(org.getParentId(),result.getOrgIndexCode());
//                    OrgInfo orgInfo = syncLocation(org,config,parent);
//                    iOrgInfoService.save(orgInfo);
//                }
//            }
//            if(org.getType() == OrganizationTypeEnum.ORG.getId().intValue()){
//                HashMap<Integer, String> parent = new HashMap<>();
//                OrgInfo result = iOrgInfoService.getOrgInfo(org.getParentId(), config.getProductId());
//                if(null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
//                    parent.put(org.getParentId(),result.getOrgIndexCode());
//                    OrgInfo orgInfo = syncOrg(org,config,parent);
//                    iOrgInfoService.save(orgInfo);
//                }
//            }
//        });
    }

    private void initOrganization(PedestrianIntegrationConfigDTO config, Integer enterpriseId) {
        HashMap<Integer, String> parent = new HashMap<>();
        List<OrgInfo> orgInfoList = iOrgInfoService.getList(config.getProductId(), null);
        OrganizationQuery query = new OrganizationQuery();
        query.setEnterpriseId(enterpriseId);
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.getId().intValue()));
        List<Organization> organizationListMap = iProjectCentService.organizationList(query);
        parent.put(organizationListMap.get(0).getParentId(), "0");
        OrgInfo result = orgInfoList.stream().filter(s -> s.getId().equals(organizationListMap.get(0).getId())).findAny().orElse(null);
        if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
            parent.put(organizationListMap.get(0).getId(), result.getOrgIndexCode());
        } else {
            OrgInfo orgInfo = syncOrg(organizationListMap.get(0), config, parent);
            parent.put(organizationListMap.get(0).getId(), orgInfo.getOrgIndexCode());
            iOrgInfoService.save(orgInfo);
        }
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ORG.getId().intValue()));
        List<Organization> organizationAreaList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationAreaList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationAreaList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncOrg(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
    }

    private OrgInfo syncOrg(Organization org, PedestrianIntegrationConfigDTO config, HashMap<Integer, String> parent) {
        if (StringUtils.isNotEmpty(parent.getOrDefault(org.getParentId(), ""))) {
            Organization organization = new Organization();
            organization.setId(null);
            organization.setName(org.getName());
            organization.setParentId(Integer.parseInt(parent.get(org.getParentId())));
            String orgId = userItcHandler.addOrg(organization, config);
            if (StringUtils.isNotEmpty(orgId)) {
                OrgInfo orgInfo = new OrgInfo();
                orgInfo.setId(org.getId());
                orgInfo.setParentId(org.getParentId());
                orgInfo.setOrgName(org.getName());
                orgInfo.setProductId(config.getProductId());
                orgInfo.setOrgIndexCode(orgId);//存储第三方地址
                return orgInfo;
            }
        }
        return null;
    }

    private void initLocation(PedestrianIntegrationConfigDTO config) {
        HashMap<Integer, String> parent = new HashMap<>();
        List<OrgInfo> orgInfoList = iOrgInfoService.getList(config.getProductId(), null);

        OrganizationQuery query = new OrganizationQuery();
        query.setProjectIds(Collections.singletonList(config.getProjectId()));
        query.setTypes(Arrays.asList(OrganizationTypeEnum.PROJECT.getId().intValue()));
        List<Organization> organizationListMap = iProjectCentService.organizationList(query);
        parent.put(organizationListMap.get(0).getParentId(), "0");
        OrgInfo result = orgInfoList.stream().filter(s -> s.getId().equals(organizationListMap.get(0).getId())).findAny().orElse(null);
        if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
            parent.put(organizationListMap.get(0).getId(), result.getOrgIndexCode());
            //return ;//空间结构已经初始化过 不需要再初始化
        } else {
            OrgInfo orgInfo = syncLocation(organizationListMap.get(0), config, parent);
            parent.put(organizationListMap.get(0).getId(), orgInfo.getOrgIndexCode());
            iOrgInfoService.save(orgInfo);
        }

        query.setTypes(Arrays.asList(OrganizationTypeEnum.PUBLIC_AREA.getId().intValue(), OrganizationTypeEnum.AREA.getId().intValue()));
        List<Organization> organizationAreaList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationAreaList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationAreaList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncLocation(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }

        query.setTypes(Arrays.asList(OrganizationTypeEnum.BUILDING.getId().intValue()));
        List<Organization> organizationBuildingList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationBuildingList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationBuildingList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncLocation(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
        query.setTypes(Arrays.asList(OrganizationTypeEnum.FLOOR.getId().intValue(), OrganizationTypeEnum.UNIT.getId().intValue()));
        List<Organization> organizationFloorList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationFloorList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationFloorList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncLocation(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ROOM.getId().intValue()));
        List<Organization> organizationROOMList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationROOMList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationROOMList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncLocation(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
    }

    private OrgInfo syncLocation(Organization org, PedestrianIntegrationConfigDTO config, HashMap<Integer, String> parent) {
        if (StringUtils.isNotEmpty(parent.getOrDefault(org.getParentId(), ""))) {
            Organization organization = new Organization();
            organization.setId(null);
            organization.setName(org.getName() + org.getId());
            organization.setParentId(Integer.parseInt(parent.get(org.getParentId())));
            String orgId = userItcHandler.addLocation(organization, config);
            if (StringUtils.isNotEmpty(orgId)) {
                OrgInfo orgInfo = new OrgInfo();
                orgInfo.setId(org.getId());
                orgInfo.setParentId(org.getParentId());
                orgInfo.setOrgName(org.getName());
                orgInfo.setProductId(config.getProductId());
                orgInfo.setOrgIndexCode(orgId);//存储第三方地址
                return orgInfo;
            }
        }
        return null;
    }

    @Override
    public void updateOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            // 如果创建的组织是ORG才能同步到海康
            Integer productId = config.getProductId();
            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue() || org.getType() == OrganizationTypeEnum.UNIT.getId().intValue() || org.getType() == OrganizationTypeEnum.FLOOR.getId().intValue() || org.getType() == OrganizationTypeEnum.AREA.getId().intValue() || org.getType() == OrganizationTypeEnum.BUILDING.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), productId);
                OrgInfo parent = iOrgInfoService.getOrgInfo(org.getParentId(), productId);
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    Organization organization = new Organization();
                    organization.setName(org.getName() + org.getId());
                    organization.setParentId(Integer.parseInt(parent.getOrgIndexCode()));
                    organization.setId(Integer.parseInt(result.getOrgIndexCode()));
                    userItcHandler.addLocation(organization, config);
                }
            }
            if (org.getType() == OrganizationTypeEnum.ORG.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), productId);
                OrgInfo parent = iOrgInfoService.getOrgInfo(org.getParentId(), productId);
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    Organization organization = new Organization();
                    organization.setName(org.getName());
                    organization.setParentId(Integer.parseInt(parent.getOrgIndexCode()));
                    organization.setId(Integer.parseInt(result.getOrgIndexCode()));
                    userItcHandler.addOrg(organization, config);
                }
            }
        });
    }

    @Override
    public void deleteOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        // 如果创建的组织是ORG才能同步到海康
        organizations.forEach(org -> {
            Integer productId = config.getProductId();
            // 如果创建的组织是ORG才能同步到海康
            if (org.getType() == OrganizationTypeEnum.ROOM.getId().intValue() || org.getType() == OrganizationTypeEnum.UNIT.getId().intValue() || org.getType() == OrganizationTypeEnum.FLOOR.getId().intValue() || org.getType() == OrganizationTypeEnum.AREA.getId().intValue() || org.getType() == OrganizationTypeEnum.BUILDING.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), productId);
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    Organization organization = new Organization();
                    organization.setId(Integer.parseInt(result.getOrgIndexCode()));
                    userItcHandler.deleteLocation(organization, config);
                    iOrgInfoService.deleteOrgInfo(result.getId(), productId);
                }
            }
            if (org.getType() == OrganizationTypeEnum.ORG.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), productId);
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    Organization organization = new Organization();
                    organization.setId(Integer.parseInt(result.getOrgIndexCode()));
                    userItcHandler.deleteOrg(organization, config);
                    iOrgInfoService.deleteOrgInfo(result.getId(), productId);
                }
            }
        });
    }

    @Override
    public String syncOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizationList) {
        log.info("同步新增组织");
//        String thirdId = userItcHandler.addOrg(organizationList.get(0),config);
//        return thirdId;
        return "";
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        OrgFactory.register(ProductEnum.ITC_BOARDROOM.id, this);
    }
}
